<?php

namespace App\Http\Controllers\UserCenter;

use App\Http\Models\User;
use App\Http\Models\Goods;
use App\Http\Models\GoodsCoupon;
use App\Http\Models\GoodsShop;
use App\Http\Models\GoodsSales;
use App\Http\Models\StatisticsUser;
use App\Http\Models\StatisticsGoodsToday;
use App\Http\Models\StatisticsGoods;
use App\Http\Models\StatisticsGoodsInfo;
use App\Http\Models\StatisticsUserKill;
use App\Http\Models\addUserOnlineGood;
use App\Http\Models\UserCapital;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Models\UserAuth;
use Auth;
use DB;

/**
 * 用户商品控制
 * Creater: lqr
 */
class UserGoodsController extends Controller
{
    /**
     * 商品链接检测，是否包含已经上线的商品
     * @param Request $request
     * @return string
     */
    public function checkLink()
    {

        $link = $this->request->link;
        if (empty($link)) {
            return json_encode(['code' => 1, 'msg' => '缺少必需的link参数！']);
        }
        $partner = "/(?<=(\?|&)id=)\w+/i";
        preg_match_all($partner, $link, $match);
        if (empty($match[0][0])) {
            return json_encode(['code' => 1, 'msg' => 'link参数不正确，未包含正确的商品ID！']);
        }
        $goodid = $match[0][0];
        if (empty($goodid)) {
            return json_encode(['code' => 1, 'msg' => 'link参数中商品ID不正确！']);
        }
        $link = substr($link, 0, stripos($link, '?')) . '?id=' . $goodid;
        $datas = Goods::select('goodsid', 'voucherprice')->where(array('goodsid' => $goodid, 'goodsstate' => 2, 'couponstate' => 0))->orderBy('voucherprice', 'asc')->first();
        if (!$datas || ($datas && $datas->userid < 10000)) {
            $message = '验证通过!';
            //验证通过后,直接获取淘宝接口数据
            $c = new \TopClient;
            $c->appkey = env('TaoBao_App_Key');
            $c->secretKey = env('TaoBao_App_Secret');
            $req = new \TbkItemInfoGetRequest;
            //$req->setFields("num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,volume");
            $req->setPlatform("1");
            $req->setNumIids($goodid);
            $resp = $c->execute($req);
            $tbk = (array)$resp->results->n_tbk_item;
            $good = array(
                'goodsid' => $goodid,
                'goodslink' => $link,
                'salecount' => $tbk['volume'],
                'images' => isset($tbk['small_images']) ? $tbk['small_images']->string[0] : ''
            );
            return json_encode(['code' => 0, 'msg' => 'ok', 'data' => $good]);
        } else {
            $message = '已经有商品正在做活动,不能再次添加!';
            return json_encode(['code' => 1, 'msg' => $message, 'data' => $datas]);
            //$message='该商品正在推广中，当前推广券后价为【'.$datas->voucherprice.'】，如有更低券后价提交，请点击【下一步】，若无更高优惠仍继续填写提交将会提交失败！';
        }

    }

    /**
     * 检测完确认下一步，根据商品链接获取商品详情
     *
     * @return string
     */
    public function TBInfo()
    {
        $gid = $this->request->gid;
        if (empty($gid)) {
            return json_encode(['code' => 1, 'msg' => '缺少必需的淘宝商品ID参数！']);
        }
        $link = $this->request->link;
        if (empty($link)) {
            return json_encode(['code' => 1, 'msg' => '缺少必需的link参数！']);
        }

        $c = new \TopClient;
        $c->appkey = env('TaoBao_App_Key');
        $c->secretKey = env('TaoBao_App_Secret');
        $req = new \TbkItemInfoGetRequest;
        //$req->setFields("num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,volume");
        $req->setPlatform("1");
        $req->setNumIids($gid);
        $resp = $c->execute($req);
        $tbk = (array)$resp->results->n_tbk_item;
        $good = array(
            'goodsid' => $gid,
            'goodslink' => $link,
            'salecount' => $tbk['volume'],
            'images' => $tbk['small_images']->string[0]
        );
        return json_encode(['code' => 0, 'msg' => 'ok', 'data' => $good]);
    }

    /**
     * 添加和修改平推单
     * @param Request $request
     * @return string
     */
    public function saveNormal(Request $request)
    {
        $uid = Auth::id();//获取当前登陆用户ID
        if (empty($uid)) {
            return json_encode(['code' => 1, 'msg' => '用户尚未登陆！']);
        }
        $link = $this->request->goodslink;
        $partner = "/(?<=(\?|&)id=)\w+/i";
        preg_match_all($partner, $link, $match);
        if (empty($match[0][0])) {
            return json_encode(['code' => 1, 'msg' => 'link参数不正确，未包含正确的商品ID！']);
        }
        $goodid = $match[0][0];
        if (empty($goodid)) {
            return json_encode(['code' => 1, 'msg' => 'link参数中商品ID不正确！']);
        }
        if (strlen($link) > 250) {
            $link = substr($link, 0, stripos($link, '?')) . '?id=' . $goodid;
            return json_encode(['code' => 1, 'msg' => '商品链接太长了,请更换！', 'data' => ['goodslink' => $link]]);
        }
        $data = $request->only([
            'goodsid',
            'goodslink',
            'goodstitle',
            'coverimage',
            'commissiontype',
            'commissionrate',
            'copywriting',
            'copywritingimage',
            'voucherprice',
            'couponlink',
            'coupontotal',
            'begintime',
            'coupontype',
            'activitytype',
            'startsales',
            'begintimetype',
            'couponmoney',
        ]);

        $error = DataValidate($data, [
            'goodsid' => 'required|numeric',
            'goodslink' => 'required|url',
            'goodstitle' => 'required',
            'coverimage' => 'required',
            'commissiontype' => 'required|numeric',
            'commissionrate' => 'required|numeric',
            'copywriting' => 'required',
            'copywritingimage' => 'required',
            'voucherprice' => 'required|numeric',
            'couponlink' => 'required|url',
            'coupontotal' => 'required|numeric',
            'begintime' => 'required|date',
            'coupontype' => 'required|numeric',
            'begintimetype' => 'required|numeric',
            'activitytype' => 'required|numeric',
            'startsales' => 'required|numeric'
        ]);

        if (count($error) > 0) {
            return json_encode(['code' => 1, 'msg' => $error]);
        }
        $gid = $request->id;
        //表示添加商品
        if (empty($gid)) {
            //判断点券
            if (!UserCapital::IsSendGoods(0)) {
                return json_encode(['code' => 1, 'msg' => '用户点券不足！']);
            }

            DB::beginTransaction(); //开启事务
            $gsid = Goods::insertGetId([
                'userid' => $uid,
                'goodsid' => $data['goodsid'],
                'goodslink' => $data['goodslink'],
                'goodstitle' => $data['goodstitle'],
                'coverimage' => json_encode(["main" => $data['coverimage']], JSON_UNESCAPED_UNICODE),// '{"main":"' . $data['coverimage'] . '"}',
                'commissiontype' => $data['commissiontype'],
                'commissionrate' => $data['commissionrate'],
                'copywriting' => json_encode(["first" => $data['copywriting']], JSON_UNESCAPED_UNICODE), //'{"first":"' . $data['copywriting'] . '"}',
                'copywritingimage' => json_encode(["first" => $data['copywritingimage']], JSON_UNESCAPED_UNICODE),// '{"first":"' . $data['copywritingimage'] . '"}',
                'voucherprice' => $data['voucherprice'],
                'begintime' => $data['begintime'],
                'begintimetype' => $data['begintimetype'],
                'created_at' => date('y-m-d h:i:s', time())
            ]);
            //var_dump($gid);

            $cid = GoodsCoupon::insert([
                'gid' => $gsid,
                'couponlink' => $data['couponlink'],
                'coupontotal' => $data['coupontotal'],
                'coupontype' => $data['coupontype'],
                'couponmoney' => isset($data['couponmoney']) ? $data['couponmoney'] : 0,
                'created_at' => date('y-m-d h:i:s', time())
            ]);
            $shid = GoodsShop::insert([
                'gid' => $gsid,
                'activitytype' => $data['activitytype'],
                'created_at' => date('y-m-d h:i:s', time())
            ]);
            $sid = GoodsSales::insert([
                'gid' => $gsid,
                'startsales' => $data['startsales'],
                'created_at' => date('y-m-d h:i:s', time())
            ]);
            $content = '平推商品[' . $data['goodstitle'] . ']提交商品,使用' . env('Voucher_Normal_Deduct') . '点券';
            UserCapital::addUserCapital(Auth::id(), env('Voucher_Normal_Deduct'), 0, $content, $gsid);
            if ($gsid && $cid && $shid && $sid) {
                //判断是不是首单,第一单才增加数量
                $user_goods_number = Goods::where(['userid' => $uid])->count();
                if ($user_goods_number <= 1) {
                    StatisticsUser::updateOrderNum(); //增加下单用户数量
                }
                //更新日志流水
                StatisticsGoodsInfo::updateStatisticsGoods($gsid, 0, 0, 0, date('y-m-d h:i:s', time()));
                DB::commit();
                $user = UserCapital::getUserCapital(Auth::id());
                return json_encode(['code' => 0, 'msg' => 'ok', 'data' => $user]);
            } else {
                DB::rollback();//事务回滚
                return json_encode(['code' => 1, 'msg' => 'fail']);
            }
        } else {
            //获取要修改的平推单数据
            $obj = Goods::select('coverimage', 'goodsstate')->where(array('id' => $gid, 'userid' => $uid, 'goodstype' => 0))->first();
            if (empty($obj)) {
                return json_encode(['code' => 1, 'msg' => '不存在的商品数据！']);
            }
            //如果是审拒后重新发起修改,需要扣点券
            if ($obj['goodsstate'] == 3) {
                //判断点券
                if (!UserCapital::IsSendGoods(0)) {
                    return json_encode(['code' => 1, 'msg' => '用户点券不足！']);
                }
            }
            //修改封面图
            //将字符串转成json数据结构对象
            $imgs = json_decode(json_encode($obj['coverimage']), true);
            //修改第一张封面图
            $imgs["main"] = $data['coverimage'];
            //修改后的图片数组转回JSON字符串
            $imgstr = json_encode($imgs);


            DB::beginTransaction(); //开启事务
            $gsid = Goods::where(array('id' => $gid, 'userid' => $uid, 'goodstype' => 0))->update([
                'goodsid' => $data['goodsid'],
                'goodstitle' => $data['goodstitle'],
                'coverimage' => $imgstr,
                'goodsstate' => 0,
                'commissiontype' => $data['commissiontype'],
                'commissionrate' => $data['commissionrate'],
                'copywriting' => json_encode(["first" => $data['copywriting']], JSON_UNESCAPED_UNICODE),// '{"first":"' . $data['copywriting'] . '"}',
                'copywritingimage' => json_encode(["first" => $data['copywritingimage']], JSON_UNESCAPED_UNICODE),// '{"first":"' . $data['copywritingimage'] . '"}',
                'voucherprice' => $data['voucherprice'],
                'begintime' => $data['begintime'],
                'begintimetype' => $data['begintimetype'],
                'updated_at' => date('y-m-d h:i:s', time())
            ]);
            $cid = GoodsCoupon::where(array('gid' => $gid))->update([
                'couponlink' => $data['couponlink'],
                'coupontotal' => $data['coupontotal'],
                'coupontype' => $data['coupontype'],
                'couponmoney' => isset($data['couponmoney']) ? $data['couponmoney'] : 0,
                'updated_at' => date('y-m-d h:i:s', time())
            ]);
            $shid = GoodsShop::where(array('gid' => $gid))->update([
                'activitytype' => $data['activitytype'],
                'updated_at' => date('y-m-d h:i:s', time())
            ]);
            //如果是管理员审核退回重新修改,则需要扣券
            if ($obj['goodsstate'] == 3) {
                $content = '平推商品[' . $data['goodstitle'] . ']提交商品,使用' . env('Voucher_Normal_Deduct') . '点券';
                UserCapital::addUserCapital(Auth::id(), env('Voucher_Normal_Deduct'), 0, $content, $gid);
            }
            if ($gsid && $cid && $shid) {
                DB::commit();
                //更新日志流水
                if ($obj['goodsstate'] == 3) {
                    StatisticsGoodsInfo::updateStatisticsGoods($gid, 0, 0, 0, date('y-m-d h:i:s', time()), $obj['goodsstate']);
                }
                $user = UserCapital::getUserCapital(Auth::id());
                return json_encode(['code' => 0, 'msg' => 'ok', 'data' => $user]);
            } else {
                DB::rollback();//事务回滚
                return json_encode(['code' => 1, 'msg' => 'fail']);
            }
        }
    }

    /**
     * 添加和修改爆款单
     * @param Request $request
     * @return string
     */
    public function saveFire(Request $request)
    {
        $uid = Auth::id();//获取当前登陆用户ID
        if (empty($uid)) {
            return json_encode(['code' => 1, 'msg' => '用户尚未登陆！']);
        }
        $link = $this->request->goodslink;
        $partner = "/(?<=(\?|&)id=)\w+/i";
        preg_match_all($partner, $link, $match);
        if (empty($match[0][0])) {
            return json_encode(['code' => 1, 'msg' => 'link参数不正确，未包含正确的商品ID！']);
        }
        $goodid = $match[0][0];
        if (empty($goodid)) {
            return json_encode(['code' => 1, 'msg' => 'link参数中商品ID不正确！']);
        }
        if (strlen($link) > 250) {
            $link = substr($link, 0, stripos($link, '?')) . '?id=' . $goodid;
            return json_encode(['code' => 1, 'msg' => '商品链接太长了,请更换！', 'data' => ['goodslink' => $link]]);
        }
        $data = $request->only([
            'goodsid',
            'goodslink',
            'goodstitle',
            'coverimage',
            'commissiontype',
            'commissionrate',
            'copywriting',
            'copywritingimage',
            'voucherprice',
            'couponlink',
            'coupontotal',
            'begintime',
            'coupontype',
            'activitytype',
            'startsales',
            'copywriting2',
            'copywritingimage2',
            'begintimetype',
            'couponmoney'
        ]);
        $error = DataValidate($data, [
            'goodsid' => 'required|numeric',
            'goodslink' => 'required|url',
            'goodstitle' => 'required',
            'coverimage' => 'required',
            'commissiontype' => 'required|numeric',
            'commissionrate' => 'required|numeric',
            'copywriting' => 'required',
            'copywritingimage' => 'required',
            'voucherprice' => 'required|numeric',
            'couponlink' => 'required|url',
            'coupontotal' => 'required|numeric',
            'begintime' => 'required|date',
            'coupontype' => 'required|numeric',
            'activitytype' => 'required|numeric',
            'startsales' => 'required|numeric',
            'copywriting2' => 'required',
            'copywritingimage2' => 'required',
            'begintimetype' => 'required',
        ]);

        if (count($error) > 0) {
            return json_encode(['code' => 1, 'msg' => $error]);
        }
        $gid = $request->id;
        //表示添加商品
        if (empty($gid)) {
            //判断点券
            if (!UserCapital::IsSendGoods(1)) {
                return json_encode(['code' => 1, 'msg' => '用户点券不足！']);
            }
            DB::beginTransaction(); //开启事务
            $gsid = Goods::insertGetId([
                'userid' => $uid,
                'goodstype' => 1,
                'goodsstate' => 0,
                'goodsid' => $data['goodsid'],
                'goodslink' => $data['goodslink'],
                'goodstitle' => $data['goodstitle'],
                'coverimage' => json_encode(["main" => $data['coverimage']], JSON_UNESCAPED_UNICODE),//'{"main":"' . $data['coverimage'] . '"}',
                'commissiontype' => $data['commissiontype'],
                'commissionrate' => $data['commissionrate'],
                'copywriting' => json_encode(["first" => $data['copywriting'], "second" => $data['copywriting2']], JSON_UNESCAPED_UNICODE), //'{"first":"' . $data['copywriting'] . '","second":"' . $data['copywriting2'] . '"}',
                'copywritingimage' => json_encode(["first" => $data['copywritingimage'], "second" => $data['copywritingimage2']], JSON_UNESCAPED_UNICODE),// '{"first":"' . $data['copywritingimage'] . '","second":"' . $data['copywritingimage2'] . '"}',
                'voucherprice' => $data['voucherprice'],
                'begintime' => $data['begintime'],
                'begintimetype' => $data['begintimetype'],
                'created_at' => date('y-m-d h:i:s', time())
            ]);
            $cid = GoodsCoupon::insert([
                'gid' => $gsid,
                'couponlink' => $data['couponlink'],
                'coupontotal' => $data['coupontotal'],
                'coupontype' => $data['coupontype'],
                'couponmoney' => isset($data['couponmoney']) ? $data['couponmoney'] : 0,
                'created_at' => date('y-m-d h:i:s', time())
            ]);
            $shid = GoodsShop::insert([
                'gid' => $gsid,
                'activitytype' => $data['activitytype'],
                'created_at' => date('y-m-d h:i:s', time())
            ]);
            $sid = GoodsSales::insert([
                'gid' => $gsid,
                'startsales' => $data['startsales'],
                'created_at' => date('y-m-d h:i:s', time())
            ]);

            $content = '爆款商品[' . $data['goodstitle'] . ']提交商品,使用' . env('Voucher_Fire_Deduct') . '点券';
            UserCapital::addUserCapital(Auth::id(), env('Voucher_Fire_Deduct'), 0, $content, $gsid);
            if ($gsid && $cid && $shid && $sid) {
                //判断是不是首单,第一单才增加数量
                $user_goods_number = Goods::where(['userid' => $uid])->count();
                if ($user_goods_number <= 1) {
                    StatisticsUser::updateOrderNum(); //增加下单用户数量
                }
                //StatisticsGoodsToday::updateNewOrder(1);//增加未审核数量
                //StatisticsGoods::updateNewOrder(1);//增加总的未审核数量
                //更新日志流水
                StatisticsGoodsInfo::updateStatisticsGoods($gsid, 1, 0, 0, date('y-m-d h:i:s', time()));
                DB::commit();
                $user = UserCapital::getUserCapital(Auth::id());
                return json_encode(['code' => 0, 'msg' => 'ok', 'data' => $user]);
            } else {
                DB::rollback();//事务回滚
                return json_encode(['code' => 1, 'msg' => 'fail']);
            }
        } else {
            //获取要修改的爆款单数据
            $obj = Goods::select('coverimage', 'goodsstate')->where(array('id' => $gid, 'userid' => $uid, 'goodstype' => 1))->first();
            if (empty($obj)) {
                return json_encode(['code' => 1, 'msg' => '不存在的商品数据！']);
            }
            //如果是审拒后重新发起修改,需要扣点券
            if ($obj['goodsstate'] == 3) {
                //判断点券
                if (!UserCapital::IsSendGoods(1)) {
                    return json_encode(['code' => 1, 'msg' => '用户点券不足！']);
                }
            }
            //修改封面图
            //将字符串转成json数据结构对象
            $imgs = json_decode(json_encode($obj['coverimage']), true);
            //修改第一张封面图
            $imgs["main"] = $data['coverimage'];
            //修改后的图片数组转回JSON字符串
            $imgstr = json_encode($imgs);

            DB::beginTransaction(); //开启事务
            $gsid = Goods::where(array('id' => $gid, 'userid' => $uid, 'goodstype' => 1))->update([
                'goodsid' => $data['goodsid'],
                'goodslink' => $data['goodslink'],
                'goodstitle' => $data['goodstitle'],
                'coverimage' => $imgstr,
                'goodsstate' => 0,
                'commissiontype' => $data['commissiontype'],
                'commissionrate' => $data['commissionrate'],
                'copywriting' => json_encode(["first" => $data['copywriting'], "second" => $data['copywriting2']], JSON_UNESCAPED_UNICODE), //'{"first":"' . $data['copywriting'] . '","second":"' . $data['copywriting2'] . '"}',
                'copywritingimage' => json_encode(["first" => $data['copywritingimage'], "second" => $data['copywritingimage2']], JSON_UNESCAPED_UNICODE),// '{"first":"' . $data['copywritingimage'] . '","second":"' . $data['copywritingimage2'] . '"}',
                'voucherprice' => $data['voucherprice'],
                'begintime' => $data['begintime'],
                'begintimetype' => $data['begintimetype'],
                'updated_at' => date('y-m-d h:i:s', time())
            ]);
            $cid = GoodsCoupon::where(array('gid' => $gid))->update([
                'couponlink' => $data['couponlink'],
                'coupontotal' => $data['coupontotal'],
                'coupontype' => $data['coupontype'],
                'couponmoney' => isset($data['couponmoney']) ? $data['couponmoney'] : 0,
                'updated_at' => date('y-m-d h:i:s', time())
            ]);
            $shid = GoodsShop::where(array('gid' => $gid))->update([
                'activitytype' => $data['activitytype'],
                'updated_at' => date('y-m-d h:i:s', time())
            ]);
            //如果是管理员审核退回重新修改,则需要扣券
            if ($obj['goodsstate'] == 3) {
                $content = '爆款商品[' . $data['goodstitle'] . ']提交商品,使用' . env('Voucher_Fire_Deduct') . '点券';
                UserCapital::addUserCapital(Auth::id(), env('Voucher_Fire_Deduct'), 0, $content, $gid);
            }
            if ($gsid && $cid && $shid) {
                DB::commit();
                //StatisticsGoodsToday::updateNewOrder(1);//增加未审核数量
                //StatisticsGoods::updateNewOrder(1);//增加总的未审核数量
                //更新日志流水
                if ($obj['goodsstate'] == 3) {
                    StatisticsGoodsInfo::updateStatisticsGoods($gid, 1, 0, 0, date('y-m-d h:i:s', time()), $obj['goodsstate']);
                }
                $user = UserCapital::getUserCapital(Auth::id());
                return json_encode(['code' => 0, 'msg' => 'ok', 'data' => $user]);
            } else {
                DB::rollback();//事务回滚
                return json_encode(['code' => 1, 'msg' => 'fail']);
            }
        }

    }

    /**
     * 查询不同状态的商品数据
     * @return string
     */
    public function goodslist(Request $request)
    {
        $uid = Auth::id();//获取当前登陆用户ID
        if (empty($uid)) {
            return json_encode(['code' => 1, 'msg' => '用户尚未登陆！']);
        }

        $page = request('page') ? request('page') : 1;
        $type = $request->type ? $request->type : 0;
        $state = $request->state ? $request->state : 0;
        $state = $state == 2 ? [2, 4, 6] : [$state];

        $list = DB::table('goods')
            ->leftjoin('goods_sales', 'goods.id', '=', 'goods_sales.gid')
            ->leftjoin('goods_coupon', 'goods.id', '=', 'goods_coupon.gid')
            ->leftjoin('users', 'goods.userid', '=', 'users.id')
            ->leftjoin('goods_shop', 'goods_shop.gid', '=', 'goods.id')
            ->select('users.name as username',
                'goods_sales.startsales', 'goods_sales.monthsales', 'goods_sales.increment', 'goods_sales.onehoursales', 'goods_sales.twohoursales', 'goods_sales.zerosales', 'goods_sales.todaysales',
                'goods_coupon.couponlink', 'goods_coupon.coupontype', 'goods_coupon.coupontotal', 'goods_coupon.couponremain', 'goods_coupon.couponmoney', 'goods_coupon.couponstarttime', 'goods_coupon.couponendtime', 'goods_coupon.couponcondition', 'goods_coupon.reduceprice',
                'goods_shop.shoptype', 'goods_shop.shopname', 'goods_shop.activitytype',
                'goods.id', 'goods.userid', 'goods.goodsid', 'goods.goodslink', 'goods.goodstitle', 'goods.goodstype', 'goods.goodsstate', 'goods.coverimage', 'goods.commissiontype',
                'goods.commissionrate', 'goods.copywriting', 'goods.copywritingimage', 'goods.couponstate', 'goods.origprice', 'goods.voucherprice', 'goods.refuse', 'goods.commissiontype', 'goods.updated_at as passtime', 'goods.begintime', 'goods.created_at')
            ->where(['goods.userid' => $uid, 'goods.goodstype' => $type])
            ->whereIn('goods.goodsstate', $state)
            ->paginate(env('LIMIT'));
        return json_encode(['code' => 0, 'msg' => 'ok', 'data' => $list]);
    }

    /**
     * 过期：查询不同状态的商品数据
     * @return string
     */
    public function goodslist2()
    {
        $uid = Auth::id();//获取当前登陆用户ID
        if (empty($uid)) {
            return json_encode(['code' => 1, 'msg' => '用户尚未登陆！']);
        }
        $type = request('type') ? request('type') : 0;
        $state = request('state') ? request('state') : 0;
        $limit = env('LIMIT');
        $datas = null;
        if ($state == 0) {
            $datas = DB::table('goods')
                ->leftjoin('goods_sales', 'goods.id', '=', 'goods_sales.gid')
                ->leftjoin('goods_coupon', 'goods.id', '=', 'goods_coupon.gid')
                ->leftjoin('users', 'goods.userid', '=', 'users.id')
                ->leftjoin('goods_shop', 'goods.id', '=', 'goods_shop.gid')
                ->select('goods.id', 'goods.goodsid', 'goods.goodslink', 'goods.goodstitle', 'goods.coverimage', 'goods.copywriting', 'goods.copywritingimage',
                    'goods.origprice', 'goods.commissiontype', 'goods.voucherprice', 'goods.created_at', 'goods.begintime', 'goods.commissionrate', 'goods.commissiontype',
                    'goods.goodsstate', 'goods.coverimage', 'goods_coupon.coupontotal', 'goods_coupon.couponremain', 'goods_coupon.couponlink', 'goods_coupon.reduceprice',
                    'goods.coverimage', 'users.name as username', 'goods.refuse',
                    'goods_shop.shoptype', 'goods_shop.shopname', 'goods_shop.activitytype', 'goods_sales.onehoursales',
                    'goods_sales.twohoursales', 'goods_sales.todaysales', 'goods_sales.monthsales', 'goods_sales.increment'
                )->where(array('goods.userid' => $uid, 'goods.goodstype' => $type, 'goods.goodsstate' => 0))
                ->orderBy('goods.id', 'desc')
                ->paginate($limit);
        } else if ($state == 2) {
            $datas = DB::table('goods')
                ->leftjoin('goods_sales', 'goods.id', '=', 'goods_sales.gid')
                ->leftjoin('goods_coupon', 'goods.id', '=', 'goods_coupon.gid')
                ->leftjoin('goods_audit', 'goods.id', '=', 'goods_audit.gid')
                ->leftjoin('users', 'goods.userid', '=', 'users.id')
                ->leftjoin('goods_shop', 'goods.id', '=', 'goods_shop.gid')
                ->select('goods.id', 'goods.goodsid', 'goods.goodslink', 'goods.goodstitle', 'goods.coverimage', 'goods.copywriting', 'goods.copywritingimage',
                    'goods.origprice', 'goods.commissiontype', 'goods.voucherprice', 'goods.created_at', 'goods.begintime', 'goods.commissionrate', 'goods.commissiontype',
                    'goods.goodsstate', 'goods.coverimage', 'goods_coupon.coupontotal', 'goods_coupon.couponremain', 'goods_coupon.couponlink', 'goods_coupon.reduceprice',
                    'goods.coverimage', 'goods_audit.created_at as passtime', 'users.name as username', 'goods.refuse',
                    'goods_shop.shoptype', 'goods_shop.shopname', 'goods_shop.activitytype', 'goods_sales.onehoursales',
                    'goods_sales.twohoursales', 'goods_sales.todaysales', 'goods_sales.monthsales', 'goods_sales.increment'
                )->where(array('goods.userid' => $uid, 'goods.goodstype' => $type))
                ->whereIn('goods.goodsstate', array(1, 2, 4))
                ->whereRaw('goods_audit.id=(select max(goods_audit.id) from goods_audit where goods_audit.gid=goods.id)')
                ->orderBy('id', 'desc')->paginate($limit);
        } else if ($state == 3) {
            $datas = DB::table('goods')
                ->leftjoin('goods_sales', 'goods.id', '=', 'goods_sales.gid')
                ->leftjoin('goods_coupon', 'goods.id', '=', 'goods_coupon.gid')
                ->leftjoin('goods_audit', 'goods.id', '=', 'goods_audit.gid')
                ->leftjoin('users', 'goods.userid', '=', 'users.id')
                ->leftjoin('goods_shop', 'goods.id', '=', 'goods_shop.gid')
                ->select('goods.id', 'goods.goodsid', 'goods.goodslink', 'goods.goodstitle', 'goods.coverimage', 'goods.copywriting', 'goods.copywritingimage',
                    'goods.origprice', 'goods.commissiontype', 'goods.voucherprice', 'goods.created_at', 'goods.begintime', 'goods.commissionrate', 'goods.commissiontype',
                    'goods.goodsstate', 'goods.coverimage', 'goods_coupon.coupontotal', 'goods_coupon.couponremain', 'goods_coupon.couponlink', 'goods_coupon.reduceprice',
                    'goods.coverimage', 'goods_audit.content', 'goods_audit.created_at as passtime', 'users.name as username', 'goods.refuse',
                    'goods_shop.shoptype', 'goods_shop.shopname', 'goods_shop.activitytype', 'goods_sales.onehoursales',
                    'goods_sales.twohoursales', 'goods_sales.todaysales', 'goods_sales.monthsales', 'goods_sales.increment'
                )
                ->where(array('goods.userid' => $uid, 'goods.goodstype' => $type, 'goods.goodsstate' => 3))
                ->whereRaw('goods_audit.id=(select max(goods_audit.id) from goods_audit where goods_audit.gid=goods.id)')
                ->orderBy('goods_audit.id', 'desc')
                ->paginate($limit);
        }
        return json_encode(['code' => 0, 'msg' => 'ok', 'data' => $datas]);
    }

    /**
     * 查询商品的方案预览数据
     * @return string
     */
    public function viewCopy()
    {
        $uid = Auth::id();//获取当前登陆用户ID
        if (empty($uid)) {
            return json_encode(['code' => 1, 'msg' => '用户尚未登陆！']);
        }
        $id = $this->request->id;
        if (empty($id)) {
            return json_encode(['code' => 1, 'msg' => '缺少必需的商品ID参数！']);
        }
        $datas = DB::table('goods')
            ->join('goods_shop', 'goods.id', '=', 'goods_shop.gid')
            ->join('goods_sales', 'goods.id', '=', 'goods_sales.gid')
            ->join('goods_coupon', 'goods.id', '=', 'goods_coupon.gid')
            ->join('users', 'goods.userid', '=', 'users.id')
            ->select('users.name as username',
                'goods.goodstitle', 'goods.coverimage', 'goods.commissiontype', 'goods.commissionrate', 'goods.copywriting', 'goods.copywritingimage', 'goods.origprice', 'goods.voucherprice', 'goods.created_at',
                'goods_coupon.couponlink', 'goods_coupon.coupontotal', 'goods_coupon.couponremain', 'goods_coupon.couponmoney', 'goods_coupon.reduceprice',
                'goods_sales.monthsales', 'goods_sales.increment', 'goods_sales.onehoursales', 'goods_sales.twohoursales', 'goods_sales.todaysales',
                'goods_shop.shoptype', 'goods_shop.shopname', 'goods_shop.activitytype')
            ->where(array('goods.id' => $id, 'goods.userid' => $uid))->first();
        return json_encode(['code' => 0, 'msg' => 'ok', 'data' => $datas]);
    }

    /**
     * 修改平推单查询数据
     * @return string
     */
    public function editView()
    {
        $uid = Auth::id();//获取当前登陆用户ID
        if (empty($uid)) {
            return json_encode(['code' => 1, 'msg' => '用户尚未登陆！']);
        }
        $id = $this->request->id;
        if (empty($id)) {
            return json_encode(['code' => 1, 'msg' => '缺少必需的商品ID参数！']);
        }
        $goods = Goods::find($id);
        if (empty($goods)) {
            return json_encode(['code' => 1, 'msg' => '不存在的商品！']);
        }
        if ($goods['goodsstate'] == 0 || $goods['goodsstate'] == 3) {
            $datas = DB::table('goods')
                ->join('goods_shop', 'goods.id', '=', 'goods_shop.gid')
                ->join('goods_sales', 'goods.id', '=', 'goods_sales.gid')
                ->join('goods_coupon', 'goods.id', '=', 'goods_coupon.gid')
                ->select('goods.id', 'goods.goodsid', 'goods.goodslink', 'goods.goodstype',
                    'goods.goodstitle', 'goods.begintimetype', 'goods.coverimage', 'goods.commissiontype', 'goods.commissionrate', 'goods.copywriting', 'goods.copywritingimage', 'goods.voucherprice', 'goods.begintime',
                    'goods_coupon.couponlink', 'goods_coupon.couponmoney', 'goods_coupon.coupontotal', 'goods_coupon.coupontype', 'goods_sales.startsales',
                    'goods_shop.activitytype')
                ->where(array('goods.id' => $id, 'goods.userid' => $uid))->first();

            return json_encode(['code' => 0, 'msg' => 'ok', 'data' => $datas]);
        } else {
            return json_encode(['code' => 1, 'msg' => '不允许修改的商品！']);
        }
    }


    /**
     * 对商品进行下架
     */
    public function off()
    {
        $uid = Auth::id();//获取当前登陆用户ID
        if (empty($uid)) {
            return json_encode(['code' => 1, 'msg' => '用户尚未登陆！']);
        }
        $id = $this->request->id;
        if (empty($id)) {
            return json_encode(['code' => 1, 'msg' => '缺少必需的商品ID参数！']);
        }
        $goods = Goods::find($id);
        if (!$goods) {
            return json_encode(['code' => 1, 'msg' => '不存在的商品数据']);
        }
        if (in_array($goods->goodsstate, [3, 4, 5, 6])) {
            return json_encode(['code' => 1, 'msg' => '该商品已撤销或已拒绝,下架,不能撤销或下架', 'data' => '']);
        }
        $goods->goodsstate = 6;
        $bool = $goods->save();
        if ($bool) {
            //增加秒杀商品统计更新
            StatisticsGoods::updateStatisticsGoods($goods->goodstype, 4);
            //统计用户在线商品状态
            StatisticsUserKill::addUserOnlineGood(Auth::id(), 4);
            return json_encode(['code' => 0, 'msg' => 'ok']);
        } else {
            return json_encode(['code' => 1, 'msg' => 'fail']);
        }
    }

    /**
     * 对商品进行撤销提交，删除商品
     */
    public function delete()
    {
        $uid = Auth::id();//获取当前登陆用户ID
        if (empty($uid)) {
            return json_encode(['code' => 1, 'msg' => '用户尚未登陆！']);
        }
        $id = $this->request->id;
        if (empty($id)) {
            return json_encode(['code' => 1, 'msg' => '缺少必需的商品ID参数！']);
        }
        $goods = Goods::find($id);
        if (!$goods) {
            return json_encode(['code' => 1, 'msg' => '不存在的商品数据']);
        }
        if ($goods->userid != $uid) {
            return json_encode(['code' => 1, 'msg' => '不属于你的商品数据']);
        }
        if ($goods->goodsstate != 0) {
            return json_encode(['code' => 1, 'msg' => '该商品已上架、已撤销或已拒绝,下架,不能撤销', 'data' => '']);
        }
        $goods->goodsstate = 5;
        $bool = $goods->save();
        if ($bool) {
            $deduct = env('Voucher_Normal_Deduct');
            if ($goods->goodstype == 1) {
                $deduct = env('Voucher_Fire_Deduct');
            }
            $content = '商品[' . $goods->goodstitle . ']审核撤回' . $deduct . '点券';
            UserCapital::addUserCapital($uid, $deduct, 1, $content, $id);
            //更新日志流水
            StatisticsGoodsInfo::updateStatisticsGoods($id, $goods->goodstype, 5, 0, date('y-m-d h:i:s', time()), 0);
            return json_encode(['code' => 0, 'msg' => 'ok']);
        } else {
            return json_encode(['code' => 1, 'msg' => 'fail']);
        }
    }
}
